package com.ruoyi.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TaskComment;
import com.ruoyi.system.service.ITaskCommentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;

/**
 * 任务评论Controller
 *
 * @author ruoyi
 * @date 2024-07-03
 */
@RestController
@RequestMapping("/system/comment")
public class TaskCommentController extends BaseController
{
    @Autowired
    private ITaskCommentService taskCommentService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询任务评论列表
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskComment taskComment)
    {
        startPage();
        List<TaskComment> list = taskCommentService.selectTaskCommentList(taskComment);
        return getDataTable(list);
    }

    /**
     * 导出任务评论列表
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:export')")
    @Log(title = "任务评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskComment taskComment)
    {
        List<TaskComment> list = taskCommentService.selectTaskCommentList(taskComment);
        ExcelUtil<TaskComment> util = new ExcelUtil<TaskComment>(TaskComment.class);
        util.exportExcel(response, list, "任务评论数据");
    }

    /**
     * 获取任务评论详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taskCommentService.selectTaskCommentById(id));
    }

    /**
     * 新增任务评论（支持星级、图片、匿名）
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:add')")
    @Log(title = "任务评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskComment taskComment)
    {
        taskComment.setUserId(getUserId());
        // images 字段处理（前端传数组时转为逗号分隔字符串）
        if (taskComment.getImages() != null && taskComment.getImages().contains("[")) {
            // 兼容前端传数组字符串
            String imgs = taskComment.getImages().replaceAll("[\\[\\]\"]", "");
            taskComment.setImages(imgs);
        }
        return toAjax(taskCommentService.insertTaskComment(taskComment));
    }

    /**
     * 修改任务评论
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:edit')")
    @Log(title = "任务评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskComment taskComment)
    {
        return toAjax(taskCommentService.updateTaskComment(taskComment));
    }

    /**
     * 删除任务评论
     */
    // @PreAuthorize("@ss.hasPermi('system:comment:remove')")
    @Log(title = "任务评论", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(taskCommentService.deleteTaskCommentByIds(ids));
    }

    /**
     * 根据任务ID获取评论列表（带用户昵称、头像、匿名、图片数组、回复等）
     */
    @GetMapping("/task/{taskId}")
    public TableDataInfo getCommentsByTaskId(@PathVariable Long taskId)
    {
        TaskComment taskComment = new TaskComment();
        taskComment.setTaskId(taskId);
        startPage();
        List<TaskComment> list = taskCommentService.selectTaskCommentList(taskComment);
        // 封装VO
        List<Object> voList = list.stream().map(c -> {
            SysUser user = sysUserService.selectUserById(c.getUserId());
            boolean anonymous = c.getIsAnonymous() != null && c.getIsAnonymous() == 1;
            return new java.util.HashMap<String, Object>() {{
                put("id", c.getId());
                put("userId", c.getUserId());
                put("userName", anonymous ? "匿名用户" : (user != null ? user.getNickName() : ""));
                put("userAvatar", anonymous ? "/static/default-avatar.png" : (user != null ? user.getAvatar() : ""));
                put("isAnonymous", c.getIsAnonymous());
                put("star", c.getStar());
                put("content", c.getContent());
                put("images", c.getImages() != null && !c.getImages().isEmpty() ? Arrays.asList(c.getImages().split(",")) : new java.util.ArrayList<>());
                put("reply", c.getReply());
                put("replyTime", c.getReplyTime());
                put("parentId", c.getParentId());
                put("createTime", c.getCreateTime());
            }};
        }).collect(Collectors.toList());
        return getDataTable(voList);
    }

    /**
     * 发布者回复评论
     */
    @PostMapping("/reply")
    public AjaxResult reply(@RequestBody TaskComment comment) {
        // 只允许发布者回复
        // 可加权限校验
        if (comment.getId() == null || comment.getReply() == null) {
            return AjaxResult.error("参数错误");
        }
        TaskComment update = new TaskComment();
        update.setId(comment.getId());
        update.setReply(comment.getReply());
        update.setReplyTime(new java.util.Date());
        return toAjax(taskCommentService.updateTaskComment(update));
    }
} 